<template>

  <div>
    <!-- 导入对话框 -->
    <lam-dialog :title="title" :visible.sync="open" width="400px" append-to-body @close="clear" :close-on-click-modal="false" :widthResize='false'>
      <el-upload ref="upload" accept=".xlsx, .xls" :headers="headers" :multiple="multipleSelect" :limit="fileLimit" :on-exceed="exceedHandler"
        :action="uploadUrl + '?updateSupport=' + updateSupport" :disabled="isUploading" :auto-upload="false" drag
        :on-progress="handleProgress" :on-success="handleSuccess" :on-error="handleError" >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或 <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-checkbox v-model="updateSupport" v-if="supportUpd" >已存在则更新</el-checkbox>
          <el-link type="primary" style="float:right;" @click="downloadTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅支持导入 <span :style="formatStyle">xls、xlsx</span> 格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm" :loading="isUploading">确 定</el-button>
        <el-button @click="open = false">取 消</el-button>
      </div>
    </lam-dialog>

    <ImportResult ref="importResult" />

    <DownloadIframe ref="downloadIframe" />

  </div>

</template>

<script>
  import {getToken} from "@/utils/auth";
  import {httpGet, httpPost} from '@/api';
  import ImportResult from './ImportResult';
  import DownloadIframe from '../download/DownloadIframe';

  export default {
    name: "ToImport",
    components: {
      ImportResult,
      DownloadIframe
    },
    props:{
      supportUpd:{
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {
          Authorization: getToken()
        },
        // 上传的地址
        url: {
          upload:'',
          downloadTemplate: ''
        },
        //单个文件最大值 4M
        maxFileSize: 4,
        //是否可以一次选择多个文件
        multipleSelect: true,
        //上传文件的数量
        fileLimit: 1
      };
    },
    computed:{
      uploadUrl(){
        return this.url.upload;
      },
      formatStyle(){
        return {
          'font-weight':'bold',
          color: this.$store.state.settings.theme
        }
      },
    },
    methods: {
      /** 打开弹窗 */
      openDialog(op) {
        op = Object.assign({title:""}, op);
        this.title = op.title;
        this.open = true;
        this.url.upload = op.uploadUrl;
        this.url.downloadTemplateUrl = op.downloadTemplateUrl;
      },

      clear(){
        this.$refs.upload.clearFiles();
      },

      /** 下载模板操作 */
      downloadTemplate() {
        let proms;
        if(this.url.downloadTemplateUrl instanceof Function){
          proms = this.url.downloadTemplateUrl();
        }else{
          proms = httpGet(this.url.downloadTemplateUrl);
        }
        proms.then((res) => {
            // this.$commonDownload(res.data);
            this.$refs.downloadIframe.download(res.data)
        });
      },

      // 文件上传中处理
      handleProgress(event, file, fileList) {

      },
      // 提交上传文件
      submitFileForm() {
        //this.$refs.upload.submit();
        let { uploadFiles } = this.$refs.upload;
        if(!uploadFiles.length){
          this.msgError("请选择要导入的文件！");
          return ;
        }

        let formData = new FormData();
        let fileRaws = [];
        for(let i=0;i<uploadFiles.length;i++){
          if (uploadFiles[i].raw.size > this.maxFileSize * 1024 *1024) {
            this.msgError(`【${uploadFiles[i].raw.name}】不能超过${this.maxFileSize}M`)
            return
          }
          formData.append('file', uploadFiles[i].raw);
        }
        formData.append('updateSupport', this.updateSupport)

        this.isUploading = true;
        httpPost(this.uploadUrl, formData).then(res=>{
          this.handleSuccess(res);
        }).catch(()=>{}).finally(()=>{
            this.isUploading = false;
        });
      },

      // 文件上传成功处理
      handleSuccess(res, file, fileList) {
        this.isUploading = false;
        this.open = false;
        this.clear();
        this.$refs.importResult.openDialog({
          title: this.title + '结果',
          data: res.data
        });
        this.$emit('ok');
        return false;
      },

      handleError(err, file, fileList){
        this.msgError(err&&err.msg? err.msg:"导入失败！");
      },

      exceedHandler(files, fileList){
      	this.msgError('单次只能上传一个文件');
      	return false;
      }
    },
  };
</script>

<style>
</style>
